package org.example;

import java.util.concurrent.CountDownLatch;

/**
 * 该程序证明CPU执行程序的指令会乱序
 */
public class DisorderBug1 {
    private static int x = 0, y = 0;
    private static int a = 0, b = 0;

    public static void main(String[] args) throws InterruptedException {
        for(long i = 0; i < Long.MAX_VALUE; i++)
        {
            //每个循环都清零
            x = 0;
            y = 0;
            a = 0;
            b = 0;
            CountDownLatch latch = new CountDownLatch(2);
            Thread one = new Thread(new Runnable() {
                @Override
                public void run() {
                    a = 1;//step1
                    x = b;//step2
                    latch.countDown();
                }
            });

            Thread other = new Thread(new Runnable() {
                @Override
                public void run() {
                    b = 1; //step a
                    y = a; //step b
                    latch.countDown();
                }
            });
            //线程之间的操作排列组合结果(x=0,y=1) (x=1,y=1) (x=1,y=0),但是不会出现（0，0）
            //出现了（0，0）情况，那么必然是step2 step b优先执行了
            //随机执行结果 第214710次（0,0)
            one.start();
            other.start();
            latch.await();
            String result = "第" + i+ "次（"+ x + "," + y + ")";
            if(x == 0 && y == 0)
            {
                System.err.println(result);
                break;
            }
        }
    }
}
